package com.zhu.scan;

import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.filter.AnnotationTypeFilter;
import org.springframework.util.StringUtils;

import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @ClassName MyBeanScannerRegistrar
 * @Description TODO
 * @Author zhuxiongbin
 * @Date 2021-11-10 9:23
 * @Version 1.0.0
 */
public class MyBeanScannerRegistrar implements ImportBeanDefinitionRegistrar {

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        boolean acceptAllBeans = true;

        AnnotationAttributes annotationAttributes = AnnotationAttributes.fromMap(importingClassMetadata.getAnnotationAttributes(BeanScanner.class.getName()));

        MyBeansScanner beanScanner = new MyBeansScanner(registry);

        Class<? extends Annotation> annotationClass = annotationAttributes.getClass("annotationClass");
        if(!Annotation.class.equals(annotationClass)){
            acceptAllBeans = false;
            beanScanner.addIncludeFilter(new AnnotationTypeFilter(annotationClass));
        }

        String[] values = annotationAttributes.getStringArray("value");
        List<String> basePackages = new ArrayList<>(Arrays.asList(values));

        basePackages.addAll(Arrays.asList(annotationAttributes.getStringArray("basePackages")));
        if(acceptAllBeans){
            beanScanner.addIncludeFilter((metadataReader,metadataReaderFactory)->true);
        }
        beanScanner.doScan(StringUtils.toStringArray(basePackages));
    }
}
